package com.ch.mafia.service;

import com.ch.mafia.base.BaseDao;
import com.ch.mafia.base.BaseServlet;
import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONObject;

/**
 * Servlet implementation class GetGameInfoList
 */
public class GetGameInfoListService extends BaseServlet {
	private static final long serialVersionUID = 1L;

    /**
     * Default constructor. 
     */
    public GetGameInfoListService() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		super.doGet(request, response);
		JSONObject jsonParams = new JSONObject();
		JSONObject jsonResult = new JSONObject();
		JSONArray jsonArray =new JSONArray();
		try{
			if(request.getParameter("json")!=null){
				jsonParams=new JSONObject(request.getParameter("json"));
				System.out.println("jsonParams:"+jsonParams.toString());
			}
			String houseId = jsonParams.getString("houseid");
			String queue = jsonParams.getString("queue");
			String state = jsonParams.getString("state");
			boolean noStateChange = true;
			BaseDao baseDao =new BaseDao();
			int times = 10;
			while (noStateChange) {
				 List<JSONObject> list =baseDao.queryList("s_gameinfo", null, "houseid = ? and queue= ? and state=?",
						new String[] {houseId,queue,state}, null,null);
				 if(list==null){
					 list =baseDao.queryList("s_gameinfo", null, "houseid = ?",
								new String[] {houseId}, null,null);
					 jsonArray = new JSONArray(list);
					 jsonResult.put("list", jsonArray);
					 noStateChange =false;
				 }else if(times>0){
					 Thread.sleep(2000);
					 times--;
				 }
			}
			jsonResult.put("result",SUCCESS);
		}catch (Exception e) {
			e.printStackTrace();
			try{
				jsonResult.put("result",FAIL);
			}catch (Exception ex) {
				ex.printStackTrace();
			}
		}
		response.getWriter().print(jsonResult.toString());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
